package com.yanxu.threadandobjectmethods;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2024/11/10-2024
 * @Description: 使用 notifyAll 可以将所有处于 waiting 状态的线程全部唤醒。
 */
public class Wait_NotifyOrNotifyAll {
    public static Object lock_object = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                synchronized (lock_object){
                    System.out.println("线程1获取到了锁!!!");
                    try {
                        Thread.sleep(100);
                        lock_object.wait();
                        System.out.println("线程1 继续执行!!!");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            public void run() {
                synchronized (lock_object){
                    System.out.println("线程2获取到了锁!!!");
                    try {
                        Thread.sleep(100);
                        lock_object.wait();
                        System.out.println("线程2 继续执行!!!");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        Thread thread3 = new Thread(new Runnable() {
            public void run() {
                synchronized (lock_object){
                    System.out.println("线程3 获取到了锁!!!");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    lock_object.notifyAll();
                    System.out.println("线程3 continue 执行!!!");
                }
            }
        });

        thread1.start();
        thread2.start();
        Thread.sleep(500);
        thread3.start();
    }
}